package site.brood.common.core.web;


import lombok.Data;
import lombok.NoArgsConstructor;
import site.brood.common.core.exception.ServiceException;

@Data
@NoArgsConstructor
public class AjaxJson<T> {

    private int code;
    private String message;
    private T data;

    private AjaxJson(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    private AjaxJson(int code, String message) {
        this.code = code;
        this.message = message;
    }

    private AjaxJson(AjaxCode ajaxCode) {
        this.code = ajaxCode.getCode();
        this.message = ajaxCode.getDesc();
    }

    private AjaxJson(AjaxCode ajaxCode, T data) {
        this.code = ajaxCode.getCode();
        this.message = ajaxCode.getDesc();
        this.data = data;
    }

    //========================= 成功 =======================================
    public static <T> AjaxJson<T> success(){
        return new AjaxJson<T>(AjaxCode.SUCCESS);
    }
    public static <T> AjaxJson<T> createBySuccessMessage(String msg){
        return new AjaxJson<T>(AjaxCode.SUCCESS.getCode(),msg);
    }
    public static <T> AjaxJson<T> success(T data){
        return new AjaxJson<T>(AjaxCode.SUCCESS, data);
    }
    public static <T> AjaxJson<T> success(String msg, T data){
        return new AjaxJson<T>(AjaxCode.SUCCESS.getCode(),msg,data);
    }

    //============================ 失败 =========================================
    public static <T> AjaxJson<T> error(){
        return new AjaxJson<T>(AjaxCode.ERROR);
    }

    public static <T> AjaxJson<T> error(int code,String msg){
        return new AjaxJson<T>(code,msg);
    }

    public static <T> AjaxJson<T> errorByMessage(String msg){
        return new AjaxJson<T>(AjaxCode.ERROR.getCode(),msg);
    }

    /**
     * 返回, 根据受影响行数的(大于0=success，小于0=error)
     */
    public static AjaxJson createByCount(int count) {
        if (count > 0) {
            return AjaxJson.success();
        }
        return AjaxJson.error();
    }

    /**
     * 返回，根据布尔值来确定最终结果的  (true=ok，false=error)
     */
    public static AjaxJson createByBoolean(Boolean b) {
        return b ? success() : error();
    }

    /**
     * 返回，根据对象是否为空来确定最终结果的  (true=ok，false=error)
     */
    public static AjaxJson createByNull(Object o) {
        if(o==null){
            return error();
        }else{
            return success(o);
        }
    }

    /**
     * 检查feign返回是否有效
     * @param result
     */
    public static void checkResponse(AjaxJson result,String serviceName){
        if(result == null){
            throw new ServiceException("无法访问服务:"+serviceName);
        }

        if (AjaxCode.SUCCESS.getCode() != result.getCode())
        {
            throw new ServiceException(result.getMessage(), result.getCode());
        }
    }
}
